var file_list = [];
var musicObjects = [];
var isInstallUploadingPlugin = true;
(function () {

    var pload_ocx_initErrorMsg,
        upload_ocx_initFlag,
        uploader_serverAddr,
        ue;
    upload_ocx = window.upload_ocx;
    upload_ocx_count = window.upload_ocx_count = 0;
    lock_list = false;
    
    window.onload = function () {
        ue = window.parent.ue;
        initTabs();
        initMusic();
    };    
    
    /** 初始化上传区域 */
    function initTabs() {
        var tabs = $G('tabhead').children;
        for (var i = 0; i < tabs.length; i++) {
            domUtils.on(tabs[i], "click", function (e) {
                var target = e.target || e.srcElement;
                setTabFocus(target.getAttribute('data-content-id'));
            });
        }
    }

    //初始化音频上传区域
    function initMusic() {
        var container = $('#filePickerReady');
        container.addClass("webuploader-container");
        var allowfilestr = '';
        var fileSize = editor.options.musicFileSizeLimit || editor.getOpt('musicMaxSize');
        var fileSizeLimit = (fileSize / (1024 * 1024)).toString().split('.')[0];
        if(fileSizeLimit == 0) {
            fileSizeLimit = (fileSize / (1024 * 1024)).toString().split('.')[0] + '.' + (fileSize / (1024 * 1024)).toString().split('.')[1].substring(0, 2);
        }
        var allowFiles = editor.options.musicFileTypes || editor.getOpt('musicAllowFiles');
        for(var i = allowFiles.length - 1; i >= 0; i --) {
            if(i === 0) {
                allowfilestr += allowFiles[i];
            } else {
                allowfilestr += allowFiles[i] + '、';
            }            
        }
        var str = '<div class="webuploader-pick">点击选择文件</div>' + 
                  '<div id="rt_rt_1bgn2vp7ppeo1re78ea49k10t1" style="position: absolute; top: 0px; left: 219px; width: 168px; height: 44px; overflow: hidden; bottom: auto; right: auto;">' + 
                  '<input id="fileInput" type="file" name="file" class="webuploader-element-invisible" multiple="multiple" onchange="addFile(this);">' + 
                  '<label style="opacity:0;filter:alpha(opacity=0);; width: 100%; height: 100%; display: block; cursor: pointer; background: rgb(255, 255, 255);" onclick="labelClick();"></label></div>' +
                  '<input id="objForGetFileName" style="opacity:0;filter:alpha(opacity=0);" type="radio" class="diyHide">' +
                  '<p style="font-size:13px;word-wrap:break-word; word-break:break-all; ">请上传不大于' + fileSizeLimit + 'MB的' + allowFiles + '格式的文件</p>';
        
        container.append(str);
        
        addOkListener();
    }
    
    function getContainer() {
        var parent = $(document.body);
        var container = $(document.createElement('div'));

        container.attr('id', 'rt_' + this.uid);
        container.css({
            position: 'absolute',
            top: '0px',
            left: '0px',
            width: '1px',
            height: '1px',
            overflow: 'hidden'
        });

        parent.append(container);
        parent.addClass('webuploader-container');

        return container;
    }
    
    function getUploadedCount() {
        return $('li').length;
    }
})();

 /**
  * 监听确认和取消两个按钮事件，用户执行插入或者清空正在播放的视频实例操作
  */
function addOkListener() {
    dialog.onok = function () {
        return insertMusic();
    };
}

/**
 * 向编辑器中插入音频
 */
function insertMusic() {
    var musicList = [];
    var addr = editor.getOpt('ftpServerInfo');
    for (var i = musicObjects.length; i > 0; i--) {
        musicList.push({
            url: addr + "UEditor/Attach/Musics/" + musicObjects[i- 1].url,
            width: 200,
            height: 23
        });
    }
//        $('.filelist').find('li').each(function() {
//            var addr = editor.getOpt('ftpServerInfo');
//            if ($(this).hasClass('success')) {
//                musicList.push({
//                    url: addr + "UEditor/Attach/Musics/" + musicObjects[$(this).index()].url,
//                    width: 200,
//                    height: 23
//                });
//            }
//        });
    
    editor.execCommand('insertmusic', musicList);
}

function labelClick() {
    $('#fileInput').trigger('click');
}

/**
 * 上传音频
 */
function doUpload(id, path, flag) {
    if(!flag) {
        setInterval(doUpload(id, path, flag), 100);
        return;
    }
    try {
        flag = false;
        var upload_ocx = initUploadOcx();
        var guid = getUid('file');
        upload_ocx.doUpload(file_list[id], 'mp3', guid);
        musicObjects.push({
            url: guid + '.mp3'
        });
        
        //进度
        var timer = setInterval(function () {
            var iChunk = parseFloat(upload_ocx.Chunk);
            var totalChunks = parseFloat(upload_ocx.Chunks);
            var uploadFlag = upload_ocx.UploadFlag;
            if(uploadFlag == 0) {
                alert("上传失败！");
                removeFile(path);
                clearInterval(timer);
            } else {
                var percent = parseFloat(iChunk / totalChunks).toFixed(4);
                var objID = 'WU_FILE_' + ( id + 1 );
                $('#' + objID + ' .progress span').css("width", (percent * 100) + "%");
                if(percent == 1) {
                    $('#' + objID).addClass('success');
                    $('#' + objID + ' .progress span').hide();
                    $('#' + objID + ' .success').show();
                    clearInterval(timer);
                    percent = 0;
                    flag = true;
                }
            }
        }, 100);
    } catch(e) {
        alert(e);
    }  
}

/**
 * 初始化上传插件
 */
function initUploadOcx() {
    var upload_ocx;
    //首次初始化
    var isExists = false;
    try {
        upload_ocx = new ActiveXObject("CSUpload.ctrlUpload");
        isExists = true;
    } catch (e) {
        upload_ocx_initErrorMsg = "上传插件CSUpload未安装!";
        upload_ocx_initFlag = false;
        alert(upload_ocx_initErrorMsg);
    }

    if (isExists) {
        //初始化ocx参数
        try {
            //if (!upload_ocx.InitServerInfo(editor.options.ftpUrl + 'UEditorUploadHandler.ashx', 2, 'ueditorupload', editor.options.savePath)) {
            var addr = editor.getOpt('ftpServerInfo');
            if (!upload_ocx.InitServerInfo(addr + 'UEditorUploadHandler.ashx', 2, 'Musics', 'UEditor')) {
                upload_ocx_initErrorMsg = "ActiveX插件初始化失败!";
                upload_ocx_initFlag = false;
                alert(upload_ocx_initErrorMsg);
            }
        } catch (e) {
            upload_ocx_initErrorMsg = "ActiveX插件初始化失败!";
            upload_ocx_initFlag = false;
            alert(upload_ocx_initErrorMsg);
        }
    }
    
    return upload_ocx;
}

/**
 * 从路径中取出文件名
 */
function getExactFileName(str) {
    var arr = str.split('\\');
    
    return arr[arr.length-1];
}


// 负责view的销毁
function removeFile() {
    var $ul = $('.filelist');
    var i = 1;
    $ul.find('li').each(function (item) {
        //var key=$(this).text()
        if($(this)[0].id != 'filePickerBlock') {
           $(this)[0].id = 'WU_FILE_' + i;
           
           i += 1;
        }
    });
    $('.info').text('选中' + file_list.length + '个文件，共' + getTotalFileSize() + 'MB。');
    //$li.off().find('.file-panel').off().end().remove();
}

 /*
  * 更改文件显示单位
  */
function changeSize(fileSize) {
    var units = ["B", "KB", "MB", "GB", "TB"];
    var index = 0;
    if (fileSize < 1024) {
        return fileSize + "B";
    } else {
        while (fileSize >= 1024) {
            fileSize = fileSize / 1024;
            index += 1;
        }
        return fileSize.toFixed(2) + units[index];
    }
}

/**
* 判断文件是否合法
*/
function getIsLegal(path) {
    var tmp = path.split('.');
    var ext = '.' + tmp[tmp.length - 1];
    //var allowTypes = ['mp3', 'aac', 'wav', 'cda', 'flac', 'm4a', 'mid', 'mka', 'mp2', 'mpa', 'mpc', 'ape', 'ofr', 'ogg', 'ra', 'wv', 'tta', 'ac3', 'dts', 'wma', 'midi'];
    var allowTypes = editor.options.musicFileTypes || editor.getOpt('musicAllowFiles');
    for(var i = allowTypes.length - 1; i >= 0; i --) {
        if(ext === allowTypes[i]) {
            return true;
        }
    }
    
    return false;
}

/**
 *  非H5用ActiveX插件获取文件大小
 */
function getLocalFileSize(filePath) {
    var fileSize;
    try {
        var axObj = new ActiveXObject("LgJCPT.ClsLgJCPT");
        fileSize = axObj.GetLocalFileLen(filePath);
    } catch (e) {
        if (isInstallUploadingPlugin) {
            alert("未安装LgJCPT.ClsLgJCPT插件!请到登陆页下载基础插件包。");
            isInstallUploadingPlugin = false;
        }
        return -1;
    }
    
    return fileSize;
}

/**
 * file change 事件，添加文件
 */
function addFile(obj) {
    var sizeLimit = editor.options.musicFileSizeLimit || editor.getOpt('musicMaxSize');
    var fileSize = getLocalFileSize(getFileName(obj));
    if (fileSize > sizeLimit) {
        //var fileSizeLimit = (sizeLimit / (1024 * 1024)).toString().split('.')[0] + '.' + (sizeLimit / (1024 * 1024)).toString().split('.')[1].substring(0, 2); ;
        /*if(fileSizeLimit == 0) {
            fileSizeLimit = (sizeLimit / (1024 * 1024)).toString().split('.')[0] + '.' + (sizeLimit / (1024 * 1024)).toString().split('.')[1].substring(0, 2);
        }*/
        alert('文件大小超出' + changeSize(sizeLimit) + '限制');
        return;
    } else if (fileSize == -1) {
        isInstallUploadingPlugin = true;
        return;
    }
    file_list.push(getFileName(obj));
    var str = '<div id="upload" class="panel focus">' +
              '<div id="queueList" class="queueList">' +
              '<div class="statusBar">' +
              '<div class="progress" style="display: none;">' +
              '<div class="file-panel" style="height: 0px;"><span class="cancel">删除</span></div>' +
              '<span class="text">0%</span>' +
              '<span class="percentage" style="width: 0%;"></span>' +
              '</div><div class="info" style="display: inline-block;">选中1个文件，共' + getTotalFileSize() + 'MB。</div>' +
              '<div class="btns">' +
              '<div id="filePickerBtn" class="webuploader-container">' +
              '<input type="hidden" id="hiddenFiles" name="hiddencolor" value="0" />' +
              '<div class="webuploader-pick">继续添加</div>' +
              '<div id="rt_rt_1bgdnai8p1re9cbse15e818qc6" style="position: absolute; top: 0px; left: 10px; width: 94px; height: 32px; overflow: hidden; bottom: auto; right: auto;">' +
              '<input id="fileInput2" onchange="addItem(this);" type="file" name="file" class="webuploader-element-invisible" multiple="multiple">'+
              '<label id="addFile" style="opacity: 0;filter:alpha(opacity=0); width: 100%; height: 100%; display: block; cursor: pointer; background: rgb(255, 255, 255);"></label></div></div>' +
              '<input id="objForGetFileName" style="opacity:0;filter:alpha(opacity=0);" type="radio" class="diyHide">' +
              '<div class="uploadBtn state-ready">开始上传</div>' +
              '</div>' +
              '</div>' +
              '<div id="dndArea" class="placeholder element-invisible">' +
              '<div class="filePickerContainer">' +
              '<div id="filePickerReady" class="webuploader-container"><div class="webuploader-pick">点击选择文件</div><div id="rt_rt_1bgdnai8m17kg6meo6mtu1uot1" style="position: absolute; top: 0px; left: 0px; width: 78px; height: 264px; overflow: hidden; bottom: auto; right: auto;"><input type="file" name="file" class="webuploader-element-invisible" multiple="multiple"><label style="opacity: 0; width: 100%; height: 100%; display: block; cursor: pointer; background: rgb(255, 255, 255);"></label></div></div>' +
              '</div>' +
              '</div>' +
              '<ul class="filelist">' +
              '<li id="WU_FILE_' + file_list.length + '"><p class="title">' + getRightFileName(getFileName(obj)) + '</p><p class="imgWrap notimage"><i class="file-preview file-type-mp3"></i></p><p class="progress"><span style="display: block; width: 0;"></span></p><div class="file-panel" style="height: 0px;"><span class="cancel">删除</span><span class="rotateRight">向右旋转</span><span class="rotateLeft">向左旋转</span></div>' +
              '<p class="error" style="' +
              (getIsLegal(getFileName(obj)) ? 'display: none;' : 'display: block;') +
              '">文件格式不允许</p><span class="success" style="display:none;"></span></li><li id="filePickerBlock" class="filePickerBlock webuploader-container"><div class="webuploader-pick"></div><div id="rt_rt_1bgdnai8o1a341jsa1esf19s41ufp4" style="position: absolute; top: 0px; left: 0px; width: 113px; height: 113px; overflow: hidden; bottom: auto; right: auto;"><input onchange="addItem(this);" type="file" name="file" class="webuploader-element-invisible" multiple="multiple">' + 
              '<label id="addFileLabel" style="opacity:0;filter:Alpha(opacity: 0); width: 100%; height: 100%; display: block; cursor: pointer; background: rgb(255, 255, 255);"></label></div></li>' +
              '</ul>' +
              '</div>' +
              '</div>';
    if(file_list.length === 1) {
        $('#tabbody').html(str);
    }
    
    $(document).on('mouseenter', '.filelist li', function () {
        $(this).find('.file-panel').stop().animate({height: 30});
    });
    $(document).on('mouseleave', '.filelist li', function () {
        $(this).find('.file-panel').stop().animate({height: 0});
    });
    
    $(document).on('click', '.file-panel span', function () {
        file_list.splice($(this).closest('li').index(), 1);
        $(this).closest('li').remove();
        removeFile();
    });
    
    $(document).on('click', '.uploadBtn', function () {
        var canUpload = true;
        for(var i = 0; i < file_list.length; i++) {
            if(getIsLegal(file_list[i])) {
                var num = $('#hiddencolor').val();
                $('#hiddencolor').val(num + 1);
                doUpload(i, file_list[i], canUpload);
            }          
        }
    });
    
    $('#addFile').on( 'click', function() {
        $('#fileInput2').trigger('click');
    });
    
    $('#addFileLabel').on('click', function() {
        $('#fileInput2').trigger('click');
    });
}

function addItem(obj) {
    var sizeLimit = editor.options.musicFileSizeLimit || editor.getOpt('musicMaxSize');
    if (getLocalFileSize(getFileName(obj)) > sizeLimit) {
        alert('文件大小超出' + changeSize(sizeLimit) + '限制');
        return;
    }
    var filename = getFileName(obj);
    file_list.push(filename);
    var str = '<li id="WU_FILE_' + file_list.length + '">' +
	'<p class="title">' +
		getExactFileName(filename) +
	'</p>' +
	'<p class="imgWrap notimage">' +
		'<i class="file-preview file-type-mp3"></i><span></span>' +
	'</p>' +
	'<p class="progress">' +
		'<span  style="display: block; width: 0;"></span>' +
	'</p>' +
	'<div class="file-panel" style="height: 0px;">' +
		'<span class="cancel">删除</span><span class="rotateRight">向右旋转</span><span class="rotateLeft">向左旋转</span>' +
	'</div><p class="error" style="' +
	(getIsLegal(getFileName(obj)) ?'display: none;' : 'display: block;') +
	'">文件格式不允许</p><span class="success" style="display: none;"/>' +
   '</li>';
    $('.info').text('选中' + file_list.length + '个文件，共' + getTotalFileSize() + 'MB。');
    if (file_list.length === 1) {
        $('#filePickerBlock').before(str);
    } else {
        $('#WU_FILE_' + (file_list.length - 1)).after(str);
    }
    
}

function getUid(prefix) {
    var counter = 0;
    var guid = (+new Date()).toString( 32 ),
        i = 0;

    for ( ; i < 5; i++ ) {
        guid += Math.floor( Math.random() * 65535 ).toString( 32 );
    }

    return (prefix || 'wu_') + guid + (counter++).toString( 32 );
}

function getRightFileName(path) {
    return path.split('\\')[path.split('\\').length - 1];
}

function getTotalFileSize() {
    if (file_list.length === 0) {
        return '0';
    }
    var totalFileSize = 0;
    for (var i = file_list.length; i > 0; i--) {
        var fileSize = getLocalFileSize(file_list[i - 1]);
        if (fileSize != -1) {
            totalFileSize += fileSize;
        }        
    }
    if (totalFileSize === 0) {
        return '0';
    }
    var result = changeSize(totalFileSize);

    return result;
}